package com.mqb.n8;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author mqb
 * @date 2021/5/2 16:13
 */
@Slf4j(topic = "c.TestShutDown")
public class TestShutdown {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(2);

        Future<String> res1 = pool.submit(() -> {
            log.debug("task 1 running...");
            Thread.sleep(1000);
            log.debug("task 1 finish..");
            return "1";
        });

        Future<String> res2 = pool.submit(() -> {
            log.debug("task 2 running...");
            Thread.sleep(2000);
            log.debug("task 2 finish..");
            return "2";
        });

        Future<String> res3 = pool.submit(() -> {
            log.debug("task 3 running...");
            Thread.sleep(3000);
            log.debug("task 3 finish..");
            return "3";
        });

        log.debug("shutdown");
        pool.shutdown();    // 不会阻塞主线程
        log.debug("other"); // shutdown() 之后会立刻打印

        // 如果想要阻塞下主线程，调用下面方法，或者使用 Future的get方法
        //pool.awaitTermination(3, TimeUnit.SECONDS);

        // shwdown 后再提交任务会抛出异常
//        Future<String> res4 = pool.submit(() -> {
//            log.debug("task 4 running...");
//            Thread.sleep(1000);
//            log.debug("task 4 finish..");
//            return "4";
//        });
    }
}
